<?php
/**
* This static class is the entry point to access files in the storage area.
*<p>The website do have a storage area (located under <i>site_data/Storage</i>).</p>
*<p>You must call <code>Storage::Get( ..file... );</code> to get an instance of StoredItem holding
* all the informations on your selected file. This will cause the StoredItem to be cached so for
*future reference its efficient and quick.</p>
*@author Willy Gardiol <willy@gardiol.org>
*@version 1.0
*@package Core
*@subpackage Storage
*/
class Storage extends BaseClassStatic
{
	static private $base_path = "site_data/storage";
	static private $storage = array();
	/**
	* Return a StoredItem containig all details on the given file/folder.
	*@param string $path Is the file or folder to collect info on
	*@return StoredItem contains all info on the $path
	*/
	static public function Get( $path = "" )
	{
		if ( !file_exists( Storage::$base_path ) )
			mkdir(Storage::$base_path);
		$full_path = Storage::$base_path."/$path";
		if ( file_exists( $full_path ) )
		{
			if ( !isset( Storage::$storage[ $path ] ) )
				Storage::$storage[ $path ] = new StoredItem( $path, Storage::$base_path );
			return Storage::$storage[ $path ];
		}
		return false;
	}
	/** 
	* Delete a store item and clear local cache.
	*@param string $path Path of item to delete
	*@return bool true if deletion successful
	*/
	static public function Delete( $path )
	{
		if ( ( $item = Storage::Get( $path ) ) !== false )
		{
			if ( !$item->GetLeaves() )
			{
				Storage::$storage = array();
				return unlink( $item );
			}
		}
		return false;
	}
	/** 
	* Create a new folder (NOT RECURSIVE!).
	*@param string $path Path of item to create
	*@return bool true if created successfully
	*@todo Check for safety here!!!
	*/
	static public function CreateFolder( $path )
	{
		if ( ( $item = Storage::Get( $path ) ) === false )
			return mkdir( Storage::$base_path."/".$path );
		return false;
	}
	/** 
	* Upload a new stored item and clear local cache.
	*@param string $path Path of item to upload
	*@param string $input name of files
	*@param bool $overwrite true if existing files are to be overwritten
	*@return bool true if upload successful
	*/
	static public function Upload( $path, $input, $overwrite = false )
	{
		if ( ( $item = Storage::Get( $path ) ) !== false )
		{
			if ( $item->Type() == "folder" )
			{
				if ( ($uploads = CoreUtils::UploadedFileGet( $input )) !== false )
				{
					foreach ( $uploads["files"] as $file )
					{
						$full_filename = (string)$item."/".$file["name"];
						if ( $overwrite || !file_exists( $full_filename ) )
						{
							if ( file_put_contents( $full_filename, $file["data"] ) === false )
								return false;
						}
					}
					return true;
				}
			}
		}
		return false;
	}
}
?>